import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, DatePicker, Form, Input, Popconfirm, Radio, Row, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import PortSelect from '../../components/common/portSelect';
import OrderDetail from '../../components/logisticsOrder/orderDetail';
import DeliveryReceiptDetail from '../../components/logisticsOrder/deliveryReceiptDetail';

const FormItem = Form.Item;
const R = require("ramda");
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;

const orderBusiness = Form.create()(class OrderBusiness extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({ type: 'deliveryReceipt/getListForPage', payload: { page: Constants.DEFAULT_PAGE } });
    }

    handleOpen = (id, disabled, cstEdit, cstInfoDisabled, returnEdit ) => {
        this.props.dispatch({
            type: 'deliveryReceipt/getById',
            payload: { id }
        })
        this.deliveryReceiptDetail.handleOpen(disabled, null, null, cstEdit, cstInfoDisabled, false, null, returnEdit, false, false );
    }

    handleOpenOrder = (record, disabled, cstEdit, businessApproval, businessOrder ) => {
        this.props.dispatch({
            type: 'order/getById',
            payload: { 
                receiptId: record.id
            }
        })
        this.orderDetail.handleOpen(null, record.orderId, disabled, cstEdit, null, businessApproval, businessOrder );
    }
    
    handleWithdraw = id => {
        let status = "1"
        this.props.dispatch({
            type: 'deliveryReceipt/updateDeliveryReceipt',
            payload: {
                id,
                status,
                onSuccess: this.handleSearch
            }
        })
    }

    handleCopy = id =>{
        this.props.dispatch({
            type: "deliveryReceipt/copyDeliveryReceipt",
            payload: { id, onSuccess: this.handleSearch }
        })
    }

    handleDelete = id => {
        this.props.dispatch({
            type: 'deliveryReceipt/deleteById',
            payload: {
                id,
                onSuccess: this.handleSearch
            }
        })
    }

    handleSearch = flag => {
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        let newPage = this.props.deliveryReceipt.page;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'deliveryReceipt/getListForPage',
            payload: {
                ...values,
                page: newPage
            }
        });
    };

    columns = [
        { title: '服务类型', key: 'serviceItems',
            render: record =>{
                return <span>{record.shipping ? "海运" : null}
                             {record.airFreight ? "空运" : null}
                             {record.portService ? (record.shipping || record.airFreight ? "/港前" : "港前") : null}
                             {record.vasService ? (record.shipping || record.airFreight || record.portService ?  "/增值" : "增值") : null}
                        </span>
            }
        },
        { title: '订单号', dataIndex: 'orderno', key: 'orderno' },
        { title: '客户名称', dataIndex: 'companyName', key: 'companyName' },
        //{ title: '船公司', dataIndex: 'd', key: 'd' },
        { title: 'SO', 
            render: record=>{
                return <span>{record.soNo ? record.soNo : '—' }</span>
            } 
        },
        {
            title: '起运港',
            render: record => {
                return <span>
                    <div>{record.loadingPortNameEn}</div>
                    <div>({record.loadingPortName})</div>
                </span>
            }
        },
        {
            title: '目的港',
            render: record => {
                return <span>
                    <div>{record.destinationPortNameEn}</div>
                    <div>({record.destinationPortName})</div>
                </span>
            }
        },
        // { title: '实际毛利润', dataIndex: 'm', key: 'm' },
        { title: '操作员', dataIndex: 'gdUserName', key: 'gdUserName' },
        {
            title: '交接单状态', render(record) {
                if (record.drStatus == '1') {
                    return '草稿';
                }else if (record.drStatus == '2') {
                    return '待接单';
                } else if (record.drStatus == '3') {
                    return '已转订单';
                } else if (record.drStatus == '4') {
                    return '市场退回'; 
                } else if(record.drStatus == '5'){
                    return '订舱中已转订单';
                }
            }   
        },
        {
            title: '跟单进展', render(record){
                if (record.orderStatus == '2') {
                    return '接单';
                } else if (record.orderStatus == '3') {
                    return '拖车';
                } else if (record.orderStatus == '4') {
                    return '报关中';
                } else if (record.orderStatus == '5') {
                    return '报关放行';
                } else if (record.orderStatus == '6') {
                    return '补料';
                } else if (record.orderStatus == '7') {
                    return '未收款';
                } else if (record.orderStatus == '8') {
                    return '已收款';
                } else if (record.orderStatus == '9') {
                    return '放单';
                } else if(record.orderStatus == '10'){
                    return '上船'
                }
            }
        },
        {
            title: '订单费用状态', render(record) {
                if (record.charge_status == '2') {
                    return '待审核';
                } else if (record.charge_status == '3') {
                    return '已审核';
                }
            }   
        },
        { title: '下单时间', dataIndex: 'createtime', key: 'createtime' },
        { title: '操作时间', dataIndex: 'chargeTime', key: 'chargeTime' },
        {
            title: '操作',
            render: (record) => {
                let editLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_EDIT} split={true}><a href="#" onClick={this.handleOpen.bind(this, record.id, false, false, true, record.drStatus == "4" ? false : true)}>修改交接单</a></RightBox>
                let viewLink = <a href="#" onClick={this.handleOpen.bind(this, record.id, true, true, false, false )}>查看交接单</a>
                let withdraw = <Popconfirm onConfirm={this.handleWithdraw.bind(this, record.id)} okText="是" cancelText="否" placement="leftTop" title={'交接单将重置成草稿状态，是否继续操作？'}>
                    <a href="#">撤回交接单</a>
                </Popconfirm>
                withdraw = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_WITHDRAW} split={true}>{withdraw}</RightBox>

                let deleteLink = <Popconfirm onConfirm={this.handleDelete.bind(this, record.id)} okText="是" cancelText="否" placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除?'}>
                    <a href="#">删除</a>
                </Popconfirm>
                deleteLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_DELETE} split={true}>{deleteLink}</RightBox>

                let feeApprovalLink = <RightBox resource={RightConstants.ORDER.ORDER_FEEAPPROVAL} split={true}><a href="#" onClick={this.handleOpenOrder.bind(this, record, false, true, false, false )}>费用审批</a></RightBox>
                let orderFeeLink = <RightBox resource={RightConstants.ORDER.ORDER_FEE_LOOK} split={true}><a href="#" onClick={this.handleOpenOrder.bind(this, record, false, true, false, true )}>订单查看</a></RightBox>
                let copyLink = <RightBox resource={RightConstants.DELIVERYRECEIPT.DELIVERYRECEIPT_COPY} split={true}><Popconfirm onConfirm={this.handleCopy.bind(this, record.id)} okText="是" cancelText="否" placement="leftTop" title={'是否确认复制该份交接单?'}>
                                     <a href="#">复制交接单</a>
                                </Popconfirm></RightBox>
                return <span>{["1", "4"].includes(record.drStatus) ? editLink : null}
                             {record.drStatus == "2" ? withdraw : null}
                             {["3", "5"].includes(record.drStatus) ? copyLink : null}
                             {record.drStatus == "1" ? deleteLink : null}
                             {record.charge_status == "2" ? feeApprovalLink : null}
                             {record.charge_status == "3" && record.drStatus == "3" ? orderFeeLink : null}
                             {viewLink}
                        </span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.deliveryReceipt.page.size,
            current: this.props.deliveryReceipt.page.page,
            total: this.props.deliveryReceipt.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.deliveryReceipt.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'deliveryReceipt/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.deliveryReceipt.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'deliveryReceipt/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            }
        }

        return (
            <div>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'客户名称'}>
                            {getFieldDecorator('cstName')
                                (
                                <Input maxLength="20" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'下单时间'}>
                            {getFieldDecorator('deliveryTime')(
                                <RangePicker
                                    style={{ width: '100%' }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'订单号'}>
                            {getFieldDecorator('orderNo')
                                (
                                <Input maxLength="20" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'SO号'}>
                            {getFieldDecorator('soNo')
                                (
                                <Input maxLength="20" />
                                )
                            }
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'起运港'}>
                            {getFieldDecorator('loadingPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>

                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'目的港'}>
                            {getFieldDecorator('destinationPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>
                    </Col>

                    <Col span={7} style={{ float: 'right' }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)} size={'default'}>查询</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('drStatus', {
                                initialValue: ""
                            })(
                                <RadioGroup style={{width: 800}} >
                                    <Radio value="">全部</Radio>
                                    <Radio value="1">草稿</Radio>
                                    <Radio value="2">待接单</Radio>
                                    <Radio value="5">订舱中已转订单</Radio>
                                    <Radio value="3">已转订单</Radio>
                                    <Radio value="4">已退回</Radio>
                                </RadioGroup>
                        )}
                        </FormItem>
                    </Col>
                </Row>

                <Table loading={this.props.loading} rowKey='id' dataSource={this.props.deliveryReceipt.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination}
                    title={() => <span style={{ color: 'red' }}>交接单信息</span>} />
                <DeliveryReceiptDetail wrappedComponentRef={(inst) => this.deliveryReceiptDetail = inst} refreshList={this.handleSearch} />
                <OrderDetail wrappedComponentRef={(inst) => this.orderDetail = inst} refreshList={this.handleSearch} />
            </div >
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.deliveryReceipt, deliveryReceipt: state.deliveryReceipt
    };
}

export default connect(mapStateToProps)(orderBusiness);
